<template>
  <div class="test-container">
    <h1>实际登录流程测试</h1>
    
    <div class="test-section">
      <h3>测试操作</h3>
      <button @click="testLoginUrl" class="test-btn">测试登录URL构建</button>
      <button @click="testActualLogin" class="test-btn">测试实际登录流程</button>
      <button @click="clearResults" class="test-btn">清除结果</button>
    </div>
    
    <div class="test-section" v-if="results.length > 0">
      <h3>测试结果</h3>
      <div v-for="(result, index) in results" :key="index" class="result-item">
        <span :class="result.success ? 'success' : 'error'">
          {{ result.success ? '✅' : '❌' }} {{ result.message }}
        </span>
      </div>
    </div>
    
    <div class="test-section" v-if="generatedUrl">
      <h3>生成的授权URL</h3>
      <div class="url-display">{{ generatedUrl }}</div>
      <div class="url-analysis">
        <h4>URL参数详细分析:</h4>
        <ul>
          <li v-for="(value, key) in parseUrlParams(generatedUrl)" :key="key">
            <strong>{{ key }}:</strong> 
            <span v-if="key === 'scope'">{{ value.substring(0, 50) }}...</span>
            <span v-else-if="key === 'redirect_uri'">{{ decodeURIComponent(value).substring(0, 50) }}...</span>
            <span v-else>{{ value }}</span>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import msalService from '@/services/msalService';

const results = ref<Array<{success: boolean, message: string}>>([]);
const generatedUrl = ref('');

function addResult(success: boolean, message: string) {
  results.value.push({ success, message });
}

function clearResults() {
  results.value = [];
  generatedUrl.value = '';
}

// 解析URL参数
function parseUrlParams(url: string): Record<string, string> {
  try {
    const urlObj = new URL(url);
    const params: Record<string, string> = {};
    urlObj.searchParams.forEach((value, key) => {
      params[key] = value;
    });
    return params;
  } catch (error) {
    return {};
  }
}

async function testLoginUrl() {
  clearResults();
  addResult(true, '开始测试登录URL构建...');
  
  try {
    // 直接调用MSAL服务的公共方法
    const url = msalService.buildAuthUrlWithFormPost();
    generatedUrl.value = url;
      
      addResult(true, 'URL构建成功');
      
      // 使用URL解析来验证参数
      const urlObj = new URL(url);
      addResult(urlObj.searchParams.get('response_mode') === 'form_post', 'URL包含正确的response_mode参数');
      addResult(urlObj.searchParams.get('response_type') === 'code', 'URL包含正确的response_type参数');
      addResult(urlObj.searchParams.get('client_id') !== null, 'URL包含client_id参数');
      addResult(urlObj.searchParams.get('scope') !== null, 'URL包含scope参数');
      addResult(urlObj.searchParams.get('redirect_uri') !== null, 'URL包含redirect_uri参数');
      addResult(urlObj.searchParams.get('state') !== null, 'URL包含state参数');
      addResult(urlObj.searchParams.get('nonce') !== null, 'URL包含nonce参数');
      
      // 检查URL长度
      addResult(url.length > 200, `URL长度合理: ${url.length} 字符`);
  } catch (error: any) {
    addResult(false, `URL构建失败: ${error.message}`);
  }
}

async function testActualLogin() {
  clearResults();
  addResult(true, '开始测试实际登录流程...');
  
  try {
    // 这里我们不会真正执行登录，只是测试URL构建
    addResult(true, '模拟登录流程开始');
    
    // 检查MSAL服务状态
    addResult(!!msalService, 'MSAL服务实例存在');
    addResult(typeof msalService.login === 'function', 'login方法可用');
    
    // 模拟登录流程中的URL构建
    const url = msalService.buildAuthUrlWithFormPost();
    generatedUrl.value = url;
    
    addResult(true, '实际登录流程URL构建成功');
    addResult(url.includes('response_mode=form_post'), '实际登录URL包含form_post模式');
    
    // 验证URL格式是否正确（不比较完整URL，因为state和nonce每次都会变化）
    const urlObj = new URL(url);
    addResult(urlObj.searchParams.get('response_mode') === 'form_post', 'URL包含正确的response_mode参数');
    addResult(urlObj.searchParams.get('response_type') === 'code', 'URL包含正确的response_type参数');
    addResult(urlObj.searchParams.get('client_id') !== null, 'URL包含client_id参数');
    addResult(urlObj.searchParams.get('scope') !== null, 'URL包含scope参数');
    addResult(urlObj.searchParams.get('redirect_uri') !== null, 'URL包含redirect_uri参数');
    addResult(urlObj.searchParams.get('state') !== null, 'URL包含state参数');
    addResult(urlObj.searchParams.get('nonce') !== null, 'URL包含nonce参数');
    
  } catch (error: any) {
    addResult(false, `实际登录流程测试失败: ${error.message}`);
  }
}
</script>

<style scoped>
.test-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.test-section {
  margin: 20px 0;
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 5px;
  background: #f9f9f9;
}

.test-btn {
  background: #007bff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  margin: 5px;
}

.test-btn:hover {
  background: #0056b3;
}

.result-item {
  margin: 5px 0;
  padding: 5px;
}

.success {
  color: #155724;
  background: #d4edda;
  padding: 2px 6px;
  border-radius: 3px;
}

.error {
  color: #721c24;
  background: #f8d7da;
  padding: 2px 6px;
  border-radius: 3px;
}

.url-display {
  background: #f8f9fa;
  padding: 10px;
  border-radius: 4px;
  font-family: monospace;
  font-size: 12px;
  word-break: break-all;
  margin: 10px 0;
  border: 1px solid #dee2e6;
}

.url-analysis {
  margin-top: 15px;
}

.url-analysis ul {
  list-style: none;
  padding: 0;
}

.url-analysis li {
  margin: 5px 0;
  padding: 5px;
  background: white;
  border-radius: 3px;
}
</style> 